// J2ME GPS Track
// Copyright (C) 2006 Dana Peters
// http://www.qcontinuum.org/gpstrack

package uns.fit.gis.gps;

import henson.midp.Float;
import org.qcontinuum.astro.*;

public class AstroInformation implements Runnable {

    private HorizontalPosition mSunPosition = null;
    private HorizontalPosition mMoonPosition = null;
    private Float mMoonPhase = null;
    private EarthPosition mEarthPosition = null;
    private UtcDate mUtcDate = null;
    
    public AstroInformation() {
        new Thread(this).start();
    }

    public HorizontalPosition getSunPosition() {
        return mSunPosition;
    }
    
    public HorizontalPosition getMoonPosition() {
        return mMoonPosition;
    }
    
    public Float getMoonPhase() {
        return mMoonPhase;
    }
    
    public void run() {
        Thread thread = Thread.currentThread();
        try {
            while (true) {
                thread.sleep(mEarthPosition == null ? 5000 : 60000);
                Gps gps = MobileGPS.getGps();
                if (gps != null && gps.getFix()) {
                    EarthPosition earthPosition = gps.getEarthPosition();
                    UtcDate utcDate = gps.getUTCDate();
                    //*** need to recalculate if position too old!
                    if (mEarthPosition == null || !mEarthPosition.getDistance(earthPosition).Less(100000)) {
                        recalculate(earthPosition, utcDate);
                        mEarthPosition = earthPosition;
                        mUtcDate = utcDate;
                    }
                }
            }
        } catch (InterruptedException e) {
        }
    }

    public void recalculate(EarthPosition earthPosition, UtcDate utcDate) {
        Float mjd = utcDate.getMJD();

        EclipticPosition sunEcliptic = Astrometric.sunPosition(mjd);
        EquitorialPosition sunEquitorial = sunEcliptic.toEquitorialPosition();
        mSunPosition = sunEquitorial.toHorizontalPosition(earthPosition, mjd);

        EclipticPosition moonEcliptic = Astrometric.moonPosition(mjd);
        EquitorialPosition moonEquitorial = moonEcliptic.toEquitorialPosition();
        mMoonPosition = moonEquitorial.toHorizontalPosition(earthPosition, mjd);

        Float E = sunEcliptic.getLongitude().Sub(moonEcliptic.getLongitude());
        // moonPhase = (1 + cos(pi - E)) / 2;
        mMoonPhase = Float.cos(Float.PI.Sub(E)).Add(new Float(1)).Div(new Float(2));
    }
    
}
